import { App } from 'vue';
import { Plugin } from 'vue';

const formatComponentName = (instance: ComponentPublicInstance | null) => {
	if (instance == instance?.$root) {
		return {
			name: 'root',
			path: 'root',
		};
	}
	return {
		name: instance?.$options?.name || 'anonymouns',
		path: instance?.$options?.__file || 'anonymouns',
	};
};

const errorHandler = (err: unknown, instance: ComponentPublicInstance | null, info: string) => {
	const { name, path } = formatComponentName(instance);
	const error = err as Error;
	console.error('Component:', name, path);
	console.error('Error:', error.name, error.message, error.stack);
	console.error('Detail:', info);
};

const warnHandler = (msg: unknown, instance: ComponentPublicInstance | null, trace: string) => {
	const { name, path } = formatComponentName(instance);
	console.log('path', window.location.href);
	console.warn('Component:', name, path);
	console.warn('warn:', msg);
	console.warn('Detail:', trace);
};

const errorHandlerPlugin: Plugin = {
	install(app: App) {
		app.config.errorHandler = errorHandler;
		app.config.warnHandler = warnHandler;
	},
};

export default errorHandlerPlugin;
